package com.example.library.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.library.common.PageResult;
import com.example.library.common.Result;
import com.example.library.dto.BaseQueryRequest;
import com.example.library.dto.BorrowRecordQueryRequest;
import com.example.library.entity.BorrowRecord;
import com.example.library.service.BorrowRecordService;
import com.example.library.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import java.util.List;

/**
 * 借阅记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/borrow-records")
@RequiredArgsConstructor
public class BorrowRecordController {

    private final BorrowRecordService borrowRecordService;
    private final JwtUtils jwtUtils;

    /**
     * 分页查询借阅记录
     */
    @GetMapping
    public PageResult<BorrowRecord> getBorrowRecordPage(BorrowRecordQueryRequest queryRequest) {
        IPage<BorrowRecord> page = borrowRecordService.getBorrowRecordPage(queryRequest);
        return PageResult.success(page);
    }

    /**
     * 查询用户的借阅记录
     */
    @GetMapping("/user/{userId}")
    public PageResult<BorrowRecord> getUserBorrowRecords(@PathVariable Long userId, BaseQueryRequest queryRequest) {
        IPage<BorrowRecord> page = borrowRecordService.getUserBorrowRecords(userId, queryRequest);
        return PageResult.success(page);
    }

    /**
     * 查询当前用户的借阅记录
     */
    @GetMapping("/my")
    public PageResult<BorrowRecord> getMyBorrowRecords(HttpServletRequest request, BaseQueryRequest queryRequest) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);

        IPage<BorrowRecord> page = borrowRecordService.getUserBorrowRecords(userId, queryRequest);
        return PageResult.success(page);
    }

    /**
     * 查询图书的借阅记录
     */
    @GetMapping("/book/{bookId}")
    public PageResult<BorrowRecord> getBookBorrowRecords(@PathVariable Long bookId, BaseQueryRequest queryRequest) {
        IPage<BorrowRecord> page = borrowRecordService.getBookBorrowRecords(bookId, queryRequest);
        return PageResult.success(page);
    }

    /**
     * 查询当前用户正在借阅的图书
     */
    @GetMapping("/my/current")
    public Result<List<BorrowRecord>> getMyCurrentBorrowedBooks(HttpServletRequest request) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);

        List<BorrowRecord> records = borrowRecordService.getCurrentBorrowedBooks(userId);
        return Result.success(records);
    }

    /**
     * 查询用户当前借阅的图书
     */
    @GetMapping("/user/{userId}/current")
    public Result<List<BorrowRecord>> getUserCurrentBorrowedBooks(@PathVariable Long userId) {
        List<BorrowRecord> records = borrowRecordService.getCurrentBorrowedBooks(userId);
        return Result.success(records);
    }

    /**
     * 查询逾期的借阅记录
     */
    @GetMapping("/overdue")
    public PageResult<BorrowRecord> getOverdueRecords(BaseQueryRequest queryRequest) {
        IPage<BorrowRecord> page = borrowRecordService.getOverdueRecords(queryRequest);
        return PageResult.success(page);
    }

    /**
     * 查询即将到期的借阅记录
     */
    @GetMapping("/due-soon")
    public PageResult<BorrowRecord> getDueSoonRecords(@RequestParam(defaultValue = "3") Integer days,
                                                      BaseQueryRequest queryRequest) {
        IPage<BorrowRecord> page = borrowRecordService.getDueSoonRecords(days, queryRequest);
        return PageResult.success(page);
    }

    /**
     * 根据ID获取借阅记录
     */
    @GetMapping("/{id}")
    public Result<BorrowRecord> getBorrowRecordById(@PathVariable Long id) {
        BorrowRecord record = borrowRecordService.getById(id);
        return Result.success(record);
    }

    /**
     * 借阅图书
     */
    @PostMapping("/borrow")
    public Result<BorrowRecord> borrowBook(HttpServletRequest request,
                                           @RequestParam Long bookId,
                                           @RequestParam(required = false) Integer borrowDays) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);

        BorrowRecord record = borrowRecordService.borrowBook(userId, bookId, borrowDays);
        return Result.success("借阅成功", record);
    }

    /**
     * 管理员代借图书
     */
    @PostMapping("/borrow/admin")
    public Result<BorrowRecord> borrowBookByAdmin(@RequestParam Long userId,
                                                  @RequestParam Long bookId,
                                                  @RequestParam(required = false) Integer borrowDays) {
        BorrowRecord record = borrowRecordService.borrowBook(userId, bookId, borrowDays);
        return Result.success("代借成功", record);
    }

    /**
     * 归还图书
     */
    @PutMapping("/{id}/return")
    public Result<Void> returnBook(@PathVariable Long id) {
        boolean success = borrowRecordService.returnBook(id);
        return success ? Result.success("归还成功") : Result.error("归还失败");
    }

    /**
     * 续借图书
     */
    @PutMapping("/{id}/renew")
    public Result<Void> renewBook(@PathVariable Long id,
                                  @RequestParam(required = false) Integer extendDays) {
        boolean success = borrowRecordService.renewBook(id, extendDays);
        return success ? Result.success("续借成功") : Result.error("续借失败");
    }

    /**
     * 检查用户是否已借阅某图书
     */
    @GetMapping("/check/borrowed")
    public Result<Boolean> hasUserBorrowedBook(@RequestParam Long userId, @RequestParam Long bookId) {
        boolean borrowed = borrowRecordService.hasUserBorrowedBook(userId, bookId);
        return Result.success(borrowed);
    }

    /**
     * 检查当前用户是否已借阅某图书
     */
    @GetMapping("/check/my-borrowed")
    public Result<Boolean> hasMyBorrowedBook(HttpServletRequest request, @RequestParam Long bookId) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);

        boolean borrowed = borrowRecordService.hasUserBorrowedBook(userId, bookId);
        return Result.success(borrowed);
    }

    /**
     * 获取用户当前借阅数量
     */
    @GetMapping("/user/{userId}/current-count")
    public Result<Long> getUserCurrentBorrowCount(@PathVariable Long userId) {
        Long count = borrowRecordService.getUserCurrentBorrowCount(userId);
        return Result.success(count);
    }

    /**
     * 获取当前用户借阅数量
     */
    @GetMapping("/my/current-count")
    public Result<Long> getMyCurrentBorrowCount(HttpServletRequest request) {
        String token = jwtUtils.getTokenFromRequest(request);
        Long userId = jwtUtils.getUserIdFromToken(token);

        Long count = borrowRecordService.getUserCurrentBorrowCount(userId);
        return Result.success(count);
    }

    /**
     * 获取用户历史借阅数量
     */
    @GetMapping("/user/{userId}/total-count")
    public Result<Long> getUserTotalBorrowCount(@PathVariable Long userId) {
        Long count = borrowRecordService.getUserTotalBorrowCount(userId);
        return Result.success(count);
    }

    /**
     * 获取图书借阅次数
     */
    @GetMapping("/book/{bookId}/count")
    public Result<Long> getBookBorrowCount(@PathVariable Long bookId) {
        Long count = borrowRecordService.getBookBorrowCount(bookId);
        return Result.success(count);
    }

    /**
     * 更新逾期状态
     */
    @PutMapping("/update-overdue")
    public Result<Integer> updateOverdueStatus() {
        int count = borrowRecordService.updateOverdueStatus();
        return Result.success("更新了" + count + "条逾期记录", count);
    }

    /**
     * 获取借阅统计信息
     */
    @GetMapping("/statistics")
    public Result<Object> getBorrowStatistics() {
        Object statistics = borrowRecordService.getBorrowStatistics();
        return Result.success(statistics);
    }

    /**
     * 获取热门图书统计
     */
    @GetMapping("/statistics/popular-books")
    public Result<List<Object>> getPopularBooksStatistics(@RequestParam(defaultValue = "10") Integer limit) {
        List<Object> statistics = borrowRecordService.getPopularBooksStatistics(limit);
        return Result.success(statistics);
    }

    /**
     * 获取活跃用户统计
     */
    @GetMapping("/statistics/active-users")
    public Result<List<Object>> getActiveUsersStatistics(@RequestParam(defaultValue = "10") Integer limit) {
        List<Object> statistics = borrowRecordService.getActiveUsersStatistics(limit);
        return Result.success(statistics);
    }

}